package com.deliinsns.app.employer;
import java.sql.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.deliinsns.app.employer.bean.Company;
import com.deliinsns.app.employer.bean.Employer;
import com.deliinsns.app.employer.bean.Store;
import com.deliinsns.app.employer.bean.Supply;
import com.deliinsns.app.security.bean.WebUser;
import com.deliinsns.sys.BasicController;
import com.deliinsns.sys.Messenger;
import com.deliinsns.sys.util.RequestUtils;
import com.deliinsns.sys.util.SystemConstant;
import com.deliinsns.sys.util.ParameterUtil;
import com.deliinsns.sys.util.UUIDFactory;
@Controller
public class EmployerController extends BasicController {
	
	 @Autowired  
     private  EmployerDao employerDao;  
	 @Autowired  
     private  CompanyDao companyDao;
	 @Autowired  
     private  StoreDao storeDao;
	 @Autowired  
     private  SupplyDao supplyDao;  
	//雇主注册
	@RequestMapping(value = "/view/employer/register", method = RequestMethod.POST)
	 public String register(HttpServletRequest request,HttpServletResponse response)throws Exception {
			Employer employer= new Employer();
			//BeanUtils.populate(employer, getParamMap(request));
			String employerType= request.getParameter("employerType");
			String username= request.getParameter("username");
			String password= request.getParameter("password");
			if(checkParam(employerType,username,password)&&StringUtils.isNumeric(employerType)){
				employer.setEmployerType(Integer.parseInt(employerType));
				employer.setName(username);
				employer.setPassword(password);
				employer.setName(request.getParameter("name"));
				employer.setEmail(request.getParameter("email"));
				employer.setTelephone(request.getParameter("telephone"));
				employer.setMobilephone(request.getParameter("mobilephone"));
				employer.setWeChat(request.getParameter("weChat"));
				employer.setId(UUIDFactory.generate());
				employer.setCreateTime(new Date(System.currentTimeMillis()));
				employer.setCredit(10);//新注册的雇主初始化信誉度为10
				if(employer.getEmployerType()==2){//dianpu 
					Store store= new Store();
					store.setId(UUIDFactory.generate());
					store.setName(request.getParameter("storeName"));
					employer.setHostId(store.getId());
					request.setAttribute("store", store);
					storeDao.save(store);
				}else if(employer.getEmployerType()==3){//企业
					Company company= new Company();
					company.setId(UUIDFactory.generate());
					company.setName(request.getParameter("companyName"));
					employer.setHostId(company.getId());
					request.setAttribute("company", company);
					companyDao.save(company);
				}
				employerDao.save(employer);
			}else{
				return "paramError";
			}
			request.getSession().setAttribute("user", employer);
			
			return "employer/index";
	 }
	
	@RequestMapping(value = "/employer", method = RequestMethod.GET)
	 public String employer(HttpServletRequest request,HttpServletResponse response)throws Exception {
		return "employer/index";
	 }
	
	
	@RequestMapping(value = "/employer/get/{employerId}", method = RequestMethod.GET)
	 public void getEmployer(@PathVariable String employerId ,HttpServletRequest request,HttpServletResponse response)throws Exception {
		Messenger msg= new  Messenger();
		if(checkParam(employerId)){				//如果所有参数都正确传入才进行相应处理
			Employer employer= employerDao.load(Employer.class, Integer.parseInt(employerId));
			  if(employer!=null){
				  msg.setBean(employer);
				  msg.setState(200);
				  msg.setMsg(SystemConstant.GET_SUCCESS);
			  }else{
				  msg.setState(202);
				  msg.setMsg(SystemConstant.GET_FAILD);
			  }
		}else{
			msg.setMsg(SystemConstant.PARAM_ERROR);
		}
		out(request,response,msg);
	 }
	
	@RequestMapping(value = "/employer/list", method = RequestMethod.GET)
	 public void listEmployer(HttpServletRequest request,HttpServletResponse response)throws Exception {
		Messenger msg= new  Messenger();
		String page= request.getParameter("page");//第几页
		String size= request.getParameter("size");//页的大小
		if(checkParam(page,size)&&ParameterUtil.allNumeric(page,size)){				//如果所有参数都正确传入才进行相应处理
			
			Integer pageNo= Integer.parseInt(page);
			Integer pageSize= Integer.parseInt(size);
			List<Employer> list= null;
			DetachedCriteria criteria = DetachedCriteria.forClass(Employer.class);
		    criteria.add(Property.forName("name").eq("name")) ;
			list= employerDao.findByCriteria(criteria,pageNo*pageSize,pageSize);
			msg.setItems(list);
			msg.setTotal(100);//此处的total有待查询？？？？？？？
		}else{
			msg.setMsg(SystemConstant.PARAM_ERROR);
		}
		out(request,response,msg);
	 }	
	
	@RequestMapping(value = "/employer/save", method = RequestMethod.POST)
	 public void saveEmployer(Employer employer,HttpServletRequest request,HttpServletResponse response)throws Exception {
		Messenger msg= new Messenger();
		String id =(employer!=null)?employer.getId():null;
		try{ 
			employerDao.saveOrUpdate(employer);
		} 
		catch(Exception e) 
		{ 
			msg.setMsg(e.getMessage());
			out(request,response,msg);
		}
		msg.setState(200);
		if(StringUtils.isNotEmpty(id))
			msg.setMsg(SystemConstant.UPDATE_SUCCESS);
		else
			msg.setMsg(SystemConstant.ADD_SUCCESS);
		out(request,response,msg);
	 }
	@RequestMapping(value = "view/employer/supply/save", method = RequestMethod.POST)
	 public void saveSupply(Supply supply,HttpServletRequest request,HttpServletResponse response)throws Exception {
		
		try{ 
			WebUser user= (WebUser) request.getSession().getAttribute("user");
			if(StringUtils.isEmpty(supply.getId())){ //新建
				supply.setId(UUIDFactory.generate());
				supply.setEmployerId(user.getId());
				supply.setState(1);
				supply.setCreateTime( new  Date(System.currentTimeMillis()));//获取当前时间 
			}else{//更新
				supply= supplyDao.getById(supply.getId());
				BeanUtils.populate(supply,RequestUtils.getParamsMap(request));
			}
			supplyDao.saveOrUpdate(supply);
		} 
		catch(Exception e) 
		{ 
			e.printStackTrace();
		}
		response.sendRedirect(request.getContextPath()+"/view/employer/supply/list");
	 }
	@RequestMapping(value = "view/employer/supply/detail", method = RequestMethod.GET)
	 public String supplyDetail(HttpServletRequest request,HttpServletResponse response)throws Exception {
		return "employer/supplyDetail";
	 }
	@RequestMapping(value = "view/employer/supply/list", method = RequestMethod.GET)
	 public String supplyList(HttpServletRequest request,HttpServletResponse response)throws Exception {
		String pageStr= request.getParameter("page");//第几页
		System.out.println("page:"+pageStr);
		String sizeStr= request.getParameter("size");//页的大小
		Integer page=1,size=10,total=0;
		if(StringUtils.isNotEmpty(pageStr)&&StringUtils.isNumeric(pageStr))
			 page=  Integer.parseInt(pageStr);
		page=	page<1?1:page;
		if(StringUtils.isNotEmpty(sizeStr)&&StringUtils.isNumeric(sizeStr))
			size=  Integer.parseInt(sizeStr);
		List<Supply> list= null;
		DetachedCriteria criteria = DetachedCriteria.forClass(Supply.class);
		criteria.addOrder(Order.desc("createTime"));  
	   // criteria.add(Property.forName("name").eq("name")) ;
		total= supplyDao.findByCriteria(criteria).size();
		list= supplyDao.findByCriteria(criteria,(page-1)*size,size);
		request.setAttribute("supplyList", list);
		request.setAttribute("size", size);//每页的大小
		request.setAttribute("page", page);//表示当前是第几页
		request.setAttribute("total", total); //表示总页数
		System.out.println("len:"+list.size());
		System.out.println("totalSize:"+total);
		return "employer/supplyList";
	 }
	@RequestMapping(value = "employer/supply/list", method = RequestMethod.GET)
	 public void supplyListData(HttpServletRequest request,HttpServletResponse response)throws Exception {
		Messenger msg= new Messenger();
		String pageStr= request.getParameter("page");//第几页
		System.out.println("page:"+pageStr);
		String sizeStr= request.getParameter("size");//页的大小
		Integer page=1,size=10,total=0;
		if(StringUtils.isNotEmpty(pageStr)&&StringUtils.isNumeric(pageStr))
			 page=  Integer.parseInt(pageStr);
		page=	page<1?1:page;
		if(StringUtils.isNotEmpty(sizeStr)&&StringUtils.isNumeric(sizeStr))
			size=  Integer.parseInt(sizeStr);
		List<Supply> list= null;
		DetachedCriteria criteria = DetachedCriteria.forClass(Supply.class);
		criteria.addOrder(Order.desc("createTime"));  
	   // criteria.add(Property.forName("name").eq("name")) ;
		total= supplyDao.findByCriteria(criteria).size();
		list= supplyDao.findByCriteria(criteria,(page-1)*size,size);
		request.setAttribute("supplyList", list);
		request.setAttribute("size", size);//每页的大小
		request.setAttribute("page", page);//表示当前是第几页
		request.setAttribute("total", total); //表示总页数
		System.out.println("len:"+list.size());
		System.out.println("totalSize:"+total);
		msg.setState(200);
		msg.setItems(list);
        out(request, response, msg);
	 }
	@RequestMapping(value = "view/employer/supply/edit", method = RequestMethod.GET)
	 public String supplyEdit(HttpServletRequest request,HttpServletResponse response)throws Exception {
			return "employer/supplyEdit";
		 }
	@RequestMapping(value = "view/employer/supply/delete/{id}", method = RequestMethod.GET)
	 public void supplyDelete(@PathVariable String id,HttpServletRequest request,HttpServletResponse response)throws Exception {
		 Supply supply=  supplyDao.getById(id);
		 if(supply!=null){
			 supplyDao.delete(supply);
		 }
		response.sendRedirect(request.getContextPath()+"/view/employer/supply/list");
	 }
	
	@RequestMapping(value = "/employer/delete/{employerIds}", method = RequestMethod.POST)
	 public void deleteEmployer(@PathVariable String employerIds ,HttpServletRequest request,HttpServletResponse response)throws Exception {
		Messenger msg= new Messenger();
		if(checkParam(employerIds)){				//如果所有参数都正确传入才进行相应处理
			try{
				String hql = "from Employer m where m.id in"+"("+employerIds+")";
				List<Employer> employers= employerDao.findByHql(hql);
				employerDao.delete(employers);
				msg.setState(200);
				msg.setMsg(SystemConstant.DELETE_SUCCESS);
			}catch(Exception e){
				msg.setMsg(e.getMessage());
				out(request,response,msg);
			}
		}else{
			msg.setMsg(SystemConstant.PARAM_ERROR);
		}
		out(request,response,msg);
	 }
	

}
